package com.Jasper.service;

import com.Jasper.domain.Ebook;
import com.Jasper.mapper.EbookMapper;
import com.Jasper.req.EbookQueryReq;
import com.Jasper.req.EbookSaveReq;
import com.Jasper.resp.PageResp;
import com.Jasper.util.CopyUtil;
import com.Jasper.util.SnowFlake;
import com.Jasper.vo.EbookResp;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;


@Service
public class EbookService {
    private static final Logger LOG = LoggerFactory.getLogger(EbookService.class);

    @Autowired
    private EbookMapper ebookMapper;

    @Resource
    private SnowFlake snowFlake;

    public PageResp<EbookResp> list(EbookQueryReq req) {
        QueryWrapper qw = new QueryWrapper<>();
        if (!ObjectUtils.isEmpty(req.getName())) {
            Object like = qw.like(Ebook.COL_NAME,req.getName());
        }
        PageHelper.startPage(req.getPage(), req.getSize());
//        需要把Ebook返回值转换成EbookResp
        List<Ebook> ebookList = ebookMapper.selectList(qw);

        PageInfo<Ebook> pageInfo = new PageInfo<>(ebookList);
        LOG.info("总行数：{}", pageInfo.getTotal());
        LOG.info("总页数：{}", pageInfo.getPages());


        List<EbookResp> list = CopyUtil.copyList(ebookList, EbookResp.class);


        PageResp<EbookResp> pageResp = new PageResp();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);
        return pageResp;


    }

    /**
     * 修改或者保存
     * @param req
     */
    public void save(EbookSaveReq req) {
        Ebook ebook = CopyUtil.copy(req, Ebook.class);
        if (ObjectUtils.isEmpty(req.getId())) {
            // 新增
            ebook.setId(snowFlake.nextId());
            ebookMapper.insert(ebook);
        } else {
            // 更新
            ebookMapper.updateById(ebook);
        }
    }

    /**
     * 删除
     * @param id
     */
    public void delete(Long id) {
        ebookMapper.deleteByPrimaryKey(id);
    }
}
